const express = require( 'express' );
const multer  = require('multer');

const upload = multer( { dest: 'uploads/' } );

const port = 8080 ;
const app = express();

// 处理静态资源
app.use( express.static( 'public' ) );

// 处理 content-type 为 "application/x-www-form-urlencoded" 表单
app.use( express.urlencoded( { extended: false } ) );

// 处理 content-type 为 "text/plain" 表单
app.use( express.text() );

// 处理 content-type 为 "application/json" 表单
app.use( express.json() );

app.use( '/request' , (req,resp) => {
    let action = req.method ; // 获取请求方式(即HTTP动作)
    let url = req.originalUrl ;
    let protocol = req.protocol.toUpperCase() + '/' + req.httpVersion ;
    console.log( '请求行: ' );
    console.log( action , url , protocol );

    console.log( '请求头: ' );
    let headerFieldNames = Object.getOwnPropertyNames( req.headers );
    headerFieldNames.forEach( name => {
        let value = req.headers[ name ];
        console.log( name , '=' , value );
    });

    console.log( '空行' );

    console.log( '请求体: ' );
    console.log( req.body );

    // 响应
    resp.send( '<p>请求结束</p>' );
});

let first = upload.single( 'headImage' );
console.log( first );

let second = (req,resp) => {

    console.log( '请求体: ' );
    console.log( req.body );
    console.log( req.file );

    resp.send( '<div>传是传上来了，成不成功不知道</div>' );
}

app.post( '/upload' , first , second );

app.all( '/response' , (req,resp) => {
    console.log( req.method , req.originalUrl );
    console.log( req.body );
    console.log( req.body.username , req.body.gender );
    let stu = {
        id: 1001,
        name: '朱某红',
        gender: '靓妹',
        birthdate: new Date()
    }
    resp.send( stu );
});


app.listen( port );